package com.ruoyi.oar.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ToolUtil;
import com.ruoyi.oar.domain.OarHouse;
import com.ruoyi.oar.domain.dto.OarHouseDTO;
import com.ruoyi.oar.domain.dto.OarRoomsDTO;
import com.ruoyi.oar.domain.dto.OarUserDTO;
import com.ruoyi.oar.domain.query.OarHouseQuery;
import com.ruoyi.oar.mapper.OarHouseMapper;
import com.ruoyi.oar.service.OarHouseService;
import com.ruoyi.oar.service.OarRoomsService;
import com.ruoyi.oar.service.OarUserService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 房屋Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-02-17
 */
@Service
public class OarHouseServiceImpl implements OarHouseService
{
    @Autowired
    private OarHouseMapper oarHouseMapper;
    @Autowired
    private OarRoomsService oarRoomsService;
    @Autowired
    private OarUserService oarUserService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 查询房屋
     * 
     * @param id 房屋主键
     * @return 房屋
     */
    @Override
    public Optional<OarHouseDTO> selectOarHouseById(String id) {
        return oarHouseMapper.selectOarHouseById(id).map(oarHouse -> {
            oarHouse.setOarUserList(oarUserService.selectOarUserByHouseId(id));
            oarHouse.setOarRoomsList(oarRoomsService.selectOarRoomsByHouseId(id));
            return toDto(oarHouse,true);
        });
    }

    /**
     * 查询房屋列表
     * 
     * @param oarHouseQuery 房屋
     * @return 房屋
     */
    @Override
    public List<OarHouseDTO> selectOarHouseList(OarHouseQuery oarHouseQuery) {
        return oarHouseMapper.selectOarHouseList(oarHouseQuery).stream().map(this::toDto).collect(Collectors.toList());
    }

    /**
     * 分页查询房屋列表
     * @param oarHouseQuery 房屋
     * @return
     */
    @Override
    public TableDataInfo<OarHouseDTO> findAll(OarHouseQuery oarHouseQuery) {
        List<OarHouse> list = oarHouseMapper.selectOarHouseList(oarHouseQuery);
        List<OarHouseDTO> dtoList = list.stream().map(this::toDto).collect(Collectors.toList());
        return PageUtil.getDataTable(dtoList,new PageInfo(list).getTotal());
    }


    /**
     * 新增房屋
     * 
     * @param oarHouseDTO 房屋
     * @param userType 用户类型 0用户 1民警
     * @return 结果
     */
    @Override
    @Transactional
    public int insertOarHouse(OarHouseDTO oarHouseDTO,int userType) {
        checkOarHouse(oarHouseDTO,userType);
        //oarHouseDTO.setId(SnowflakeWorker.nextId());
        ////保存从业者信息
        //oarHouseDTO.getOarUserList().forEach(oarUserDTO->{
        //    //加锁
        //    redisCache.lockExecute(RedisConstants.REDIS_USER_ADD_KEY + oarUserDTO.getUserMobile(), (lockId) -> {
        //        SysUser sysUser = userService.selectUserByPhone(oarUserDTO.getUserMobile());
        //        if(ToolUtil.isEmpty(sysUser)){//新增用户
        //            sysUser =  insertUser(oarUserDTO,oarHouseDTO.getDeptId());
        //        }
        //        oarUserDTO.setUserId(sysUser.getUserId());
        //        oarUserDTO.setHouseId(oarHouseDTO.getId());
        //        oarUserService.insertOarUser(oarUserDTO);
        //        return true;
        //    });
        //});
        //保存房间号信息
        oarHouseDTO.getOarRoomsList().forEach(oarRooms -> {
            oarRooms.setHouseId(oarHouseDTO.getId());
            oarRoomsService.insertOarRooms(oarRooms);
        });
        oarHouseDTO.setRoomsNo(oarHouseDTO.getOarRoomsList().size());
        oarHouseDTO.setTaskSort(0);
        oarHouseDTO.setTaskAuditType(0);
        return oarHouseMapper.insertOarHouse(toEntity(oarHouseDTO));
    }

    /**
     * 修改房屋人员房间信息
     * 
     * @param oarHouseDTO 房屋
     *                    * @param userType 用户类型 0用户 1民警
     * @return 结果
     */
    @Override
    @Transactional
    public int updateOarHouse(OarHouseDTO oarHouseDTO,int userType) {
        checkOarHouse(oarHouseDTO,userType);
        //更新从业者信息
        oarHouseDTO.getOarUserList().forEach(oarUserDTO->{
            ////加锁
            //redisCache.lockExecute(RedisConstants.REDIS_USER_ADD_KEY + oarUserDTO.getUserMobile(), (lockId) -> {
            //    SysUser sysUser = userService.selectUserByPhone(oarUserDTO.getUserMobile());
            //    if(ToolUtil.isEmpty(sysUser)){//新增用户
            //        sysUser = insertUser(oarUserDTO,oarHouseDTO.getDeptId());
            //    }
            //    oarUserDTO.setHouseId(oarHouseDTO.getId());
            //    oarUserDTO.setUserId(sysUser.getUserId());
            //    oarUserService.updateOarUser(oarUserDTO);
            //    return true;
            //});
        });
        //先删除房屋对应房间再插入
        oarRoomsService.deleteOarRoomsByHouseId(oarHouseDTO.getId());
        //更新房间号信息
        oarHouseDTO.getOarRoomsList().forEach(oarRooms -> {
            oarRooms.setHouseId(oarHouseDTO.getId());
            oarRoomsService.insertOarRooms(oarRooms);
        });
        oarHouseDTO.setAuditState(0);
        oarHouseDTO.setTaskSort(0);
        oarHouseDTO.setTaskAuditType(1);
        oarHouseDTO.setRoomsNo(oarHouseDTO.getOarRoomsList().size());
        return oarHouseMapper.updateOarHouse(toEntity(oarHouseDTO));
    }

    /**
     * 修改房屋
     * @param oarHouseQuery
     * @return
     */
    @Override
    public int batchUpAuditState(OarHouseQuery oarHouseQuery){
        return oarHouseMapper. batchUpAuditState(oarHouseQuery);
    }


    /**
     * 统计网约房信息审核数量
     * @param auditState
     * @return
     */
    @Override
    public int countByAuditState(Integer auditState){
        return oarHouseMapper.countByAuditState(auditState);
    }

    /**
     * 新增用户
     * @param oarUserDTO
     * @param deptId
     */
    public SysUser insertUser(OarUserDTO oarUserDTO,String deptId){
        SysUser sysUser = new SysUser();
        //sysUser.setUserId(SnowflakeWorker.nextId());
        //sysUser.setDeptId(deptId);
        //sysUser.setUserType("0");
        //sysUser.setUserName(sysUser.getUserId());
        //sysUser.setPhonenumber(oarUserDTO.getUserMobile());
        //sysUser.setStatus("0");
        //sysUser.setDelFlag("0");
        //sysUser.setCreateBy(SecurityUtils.getDefaultUserId());
        //sysUser.setRoleIds(new Long[]{100L});
        //userService.insertUser(sysUser);
        return sysUser;
    }

    /**
     * 批量删除房屋
     * 
     * @param ids 需要删除的房屋主键
     * @return 结果
     */
    @Override
    public int deleteOarHouseByIds(String[] ids) {
        return oarHouseMapper.deleteOarHouseByIds(ids);
    }

    /**
     * 删除房屋信息
     * 
     * @param id 房屋主键
     * @return 结果
     */
    @Override
    public int deleteOarHouseById(String id)
    {
        return oarHouseMapper.deleteOarHouseById(id);
    }

    /**
     * 查询当前用户房源
     * @param oarHouseQuery
     * @return
     */
    @Override
    public TableDataInfo<OarHouseDTO> selByUserId(OarHouseQuery oarHouseQuery) {
        List<OarHouse> list = oarHouseMapper.selByUserId(oarHouseQuery);
        List<OarHouseDTO> dtoList = list.stream().map(this::toDto).collect(Collectors.toList());
        return PageUtil.getDataTable(dtoList,new PageInfo(list).getTotal());
    }


    /**
    * 校验
    * @param dto
    */
    private void checkOarHouse(OarHouseDTO dto,int userType) {
        if(9==userType){
            dto.setRealTimeState(0);
            dto.setDataSources(1);
            dto.setDataDockingType(1);
            dto.setAuditState(2);
        }else  if(1==userType){
            if(ToolUtil.isEmpty(dto.getRealTimeState())){
                throw new ServiceException("实时状态不能为空");
            }
            if(ToolUtil.isEmpty(dto.getDataSources())){
                throw new ServiceException("数据来源不能为空");
            }
            if(ToolUtil.isEmpty(dto.getDataDockingType())){
                throw new ServiceException("数据对接方式不能为空");
            }
            dto.setAuditState(1);
        }else{
            dto.setRealTimeState(0);
            dto.setDataSources(0);
            dto.setDataDockingType(0);
            dto.setAuditState(0);
            dto.setIsRead(0);
            dto.setIsSend(0);
        }
    }

    private OarHouse toEntity(OarHouseDTO dto) {
        return BeanUtil.toBean(dto, OarHouse.class);
    }

    private OarHouseDTO toDto(OarHouse entity) {
        return toDto(entity, false);
    }
    /**
     * 转DTO
     *
     * @param entity
     * @param withDetail 是否查询其他信息
     * @return
     */
    private OarHouseDTO toDto(OarHouse entity, Boolean withDetail) {
            OarHouseDTO dto =  BeanUtil.toBean(entity, OarHouseDTO.class);
        List<OarRoomsDTO> roomList =oarRoomsService.selectOarRoomsByHouseId(dto.getId());
        dto.setOarRoomsList(roomList);
        if (withDetail) {

        }
        return dto;
    }
}
